<template>
    <div class="text">账号列表</div>
    <el-table :data="tableData" style="width: 100%">
        <el-table-column type="selection" width="35" />
        <el-table-column property="account" label="账号" width="280" show-overflow-tooltip />
        <el-table-column property="userGroup" label="用户组" />
        <el-table-column label="创建日期">
            <template #default="scoped">
                {{ formatTime(scoped.row.ctime) }}
            </template>
        </el-table-column>
        <el-table-column label="操作">
            <template #default="scope">
                <el-button class="eitbtn" size="small" @click="handleEdit(scope.row)">
                    编辑
                </el-button>
                <el-button size="small" type="danger" @click="confirmDelete(scope.row.id)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
        <!-- <div class="demonstration">All combined</div> -->
        <el-pagination v-model:current-page="formData.currentPage" v-model:page-size="formData.pageSize"
            :page-sizes="[5, 10, 15, 20]" :size="size" :disabled="disabled" :background="background"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
    </div>

    <el-button size="small" type="danger" @click="confirmDelete(scope.row.id)">
        批量删除
    </el-button>
    <el-button class="eitbtn" size="small" @click="handleEdit(scope.row)">
        取消选择
    </el-button>
    <el-dialog v-model="showEditModal" title="编辑用户信息" width="600">
        <el-form :model="editForm">
            <el-form-item label="账号名">
                <el-input v-model="editForm.account" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item label="用户组">
                <el-select v-model="editForm.userGroup" placeholder="请选择用户组">
                    <el-option label="超级管理员" value="超级管理员" />
                    <el-option label="普通管理员" value="普通管理员" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="showEditModal = false">取消</el-button>
                <el-button type="primary" @click="editAccountBtn">
                    确认修改
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { accountList, accountDel, accountEdit } from '@/api/account';
import { ElMessage, ElMessageBox } from 'element-plus';

// 定义数据类型
interface Account {
    id: number;
    ctime: string;
    account: string;
    userGroup: string;
    imgUrl: string;
}

// 控制编辑弹窗显示与否
const showEditModal = ref(false);
// 编辑表单数据
const editForm = reactive({
    id: '',
    account: '',
    userGroup: ''
});

// 账号列表数据
const tableData = ref<Account[]>([]);
// 数据总条数
const total = ref(0);
// 分页相关数据
const formData = reactive({
    currentPage: 1,
    pageSize: 5
});

// 格式化时间函数，将时间转换为本地日期格式
const formatTime = (time: string): string => {
    const date = new Date(time);
    return date.toLocaleDateString();
};

// 获取账号列表数据
const getAccountList = async () => {
    try {
        const res = await accountList(formData);
        tableData.value = res.data;
        total.value = res.total;
    } catch (error) {
        console.error('获取账号列表失败:', error);
        ElMessage.error('获取账号列表失败，请检查网络或联系管理员');
    }
};
getAccountList();

// 当前页发生改变时重新请求接口
const handleCurrentChange = (val: number) => {
    formData.currentPage = val;
    getAccountList();
};

// 每页数据长度发生改变时重新请求接口
const handleSizeChange = (val: number) => {
    formData.pageSize = val;
    getAccountList();
};

// 删除确认提示框
const confirmDelete = (id: number) => {
    ElMessageBox.confirm(
        '确定要永久删除该账号吗？此操作不可恢复。',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            await handleDelete(id);
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '删除已取消',
            });
        });
};

// 删除用户
const handleDelete = async (id) => {

    if (!id) {
        return;
    }
    try {
        const { code, msg } = await accountDel({ id });
        if (code === 0) {
            getAccountList();
        } else {
            ElMessage.error(msg);
        }
    } catch (error) {
        console.error('删除用户失败:', error);
        ElMessage.error('删除用户失败，请检查网络或联系管理员');
    }
};

// 处理编辑操作，填充编辑表单数据并显示编辑弹窗
const handleEdit = (row) => {
    if (!row) {
        return;
    }
    editForm.id = row.id;
    editForm.account = row.account;
    editForm.userGroup = row.userGroup;
    showEditModal.value = true;
};

// 点击弹窗中的确认修改按钮，调用接口修改账号信息
const editAccountBtn = async () => {
    try {
        const { code, msg } = await accountEdit(editForm);
        if (code === 0) {
            showEditModal.value = false;
            ElMessage.success(msg);
            getAccountList();
        } else {
            ElMessage.error(msg);
        }
    } catch (error) {
        console.error('修改用户信息失败:', error);
        ElMessage.error('修改用户信息失败，请检查网络或联系管理员');
    }
};
</script>

<style scoped>
.text {
    font-size: 20px;
    width: 100%;
    height: 50px;
    border-bottom: 2px solid #f0f2f5;
    line-height: 50px;
    margin-bottom: 20px;
}

.eitbtn {
    background: #409eff;
    color: #ffff;
}
</style>